package com.hsomandroidapp.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class BufferUtil {

	public static void write(String path, Object obj) throws IOException {
		if (StringUtils.isEmpty(path) || null == obj)
			return;
		FileOutputStream fileOutputStream = null;
		try {
			File file = new File(path);
			if (file.exists()) {
				file.delete();
			}
			file.createNewFile();
			byte[] data = serialize(obj);
			fileOutputStream = new FileOutputStream(file);
			fileOutputStream.write(data);
			fileOutputStream.close();
		} catch (IOException e) {
			throw e;
		} finally {
			if (null != fileOutputStream)
				fileOutputStream.close();
		}
	}

	public static Object read(String path) throws IOException,
			ClassNotFoundException, ClassCastException {
		if (StringUtils.isEmpty(path))
			return null;
		FileInputStream ins = new FileInputStream(path);
		byte[] readBufer = new byte[1024];
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		DataOutputStream dos = new DataOutputStream(baos);
		int len = 0;
		while ((len = ins.read(readBufer)) != -1) {
			dos.write(readBufer, 0, len);
		}
		byte[] data = baos.toByteArray();
		return deserialize(data);
	}

	public static byte[] serialize(Object obj) throws IOException {
		ByteArrayOutputStream outs = new ByteArrayOutputStream();
		ObjectOutputStream out = new ObjectOutputStream(outs);
		out.writeObject(obj);
		out.flush();
		byte[] data = outs.toByteArray();
		return data;
	}

	public static Object deserialize(byte[] data) throws IOException,
			ClassNotFoundException, ClassCastException {
		return deserialize(data, 0, data.length);
	}

	public static Object deserialize(byte[] data, int offset, int length)
			throws IOException, ClassNotFoundException, ClassCastException {
		Object obj = null;
		if (data != null) {
			InputStream instream = new ByteArrayInputStream(data, offset,
					length);
			ObjectInputStream stream = new ObjectInputStream(instream);
			obj = stream.readObject();
			instream.close();
			stream.close();
		}
		return obj;
	}

	public static int getCacheCount(int bufferLength, int bufferSize) {
		int count = bufferLength / bufferSize;
		if (bufferLength % bufferSize > 0) {
			count++;
		}
		return count;
	}

}
